<?php
/**
 * Created by PhpStorm.
 * Script Name: Tpzs.php
 * Create: 2022/4/18 10:38
 * Description: 优惠券助手处理器
 * Author: fudaoji<fdj@kuryun.cn>
 */
namespace app\bot\controller;

use app\common\model\bgf\Config;
use app\common\model\bgf\Goods;
use app\common\service\XmlMini;
use ky\Logger;

class Bgf extends Addon
{
    private $configs;
    private $toWxid = '';
    /**
     * @var Config
     */
    private $configM;
    /**
     * @var Goods
     */
    private $goodsM;
    private $xmlService;

    public function init($options = [])
    {
        parent::init($options); // TODO: Change the autogenerated stub
        $this->configM = new Config();
        $this->goodsM = new Goods();
        $this->configs = $this->configM->getConf(['admin_id' => $this->bot['admin_id']]);
        return $this;
    }

    /**
     * 群聊处理器
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function groupChatHandle(){
        if(empty($this->configs)){
            return false;
        }
        $this->toWxid = $this->groupWxid;
        if(empty($this->configs['switch']) || strpos($this->configs['groups'], $this->toWxid) === false){
            return false;
        }
        //一、接收商品卡片
        $this->receiveShareCard();
    }

    /**
     * 接收商品卡片
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    private function receiveShareCard(){
        try {
            new XmlMini($this->content['msg']);
            $xml = $this->content['msg'];
            $this->xmlService = new XmlMini($xml);
            $title = $this->xmlService->getTitle();
            $super_id = $this->xmlService->getPathParams(empty($this->configs['userid']) ? 'userId' : $this->configs['userid']);
            $xml = str_replace($super_id, 'SUPER_ID', $xml);
            if($goods = $this->goodsM->getOneByOrder(['where' => ['title' => $title], 'order' => ['id' => 'desc']])){
                $this->goodsM->updateOne(['id' => $goods['id'], 'title' => $title, 'xml' => $xml]);
            }else{
                $this->goodsM->addOne(['title' => $title, 'xml' => $xml]);
            }
        }catch (\Exception $e){
            //说明非卡片，忽略即可
            /*Logger::error($this->content['msg']);
        */
        }
    }
}